/*
  De Bruijn sequence generator javascript implementation
  Code written by Damir Vodenicarevic (https://damip.net) in march 2017.
  This work is licensed under a Creative Commons Attribution 4.0 International License.
  http://creativecommons.org/licenses/by/4.0/
*/

//Inspired by Frank Ruskey's Combinatorial Generation
//Parameters:
//  alphabet [string]: each character is an element of the alphabet
//  wordlength [positive integer]: length of a word
var debruijn= function(alphabet, wordlength) {
  var k= alphabet.length;
  var n= wordlength;
  if(k <= 0 || n <= 0) return '';
  var a= []; for(var i= 0 ; i < k*n ; ++i) a[i]= 0;
  var res= [];
  var db= function(t, p) {
    if(t > n) {
      if(n%p == 0) {
        for(var i= 1 ; i <= p ; ++i)
          res += alphabet[a[i]] + ' ';
      }
    }
    else {
      a[t]= a[t-p];
      db(t+1, p);
      for(var j= a[t-p]+1 ; j < k ; ++j) {
        a[t]= j;
        db(t+1, t);
      }
    }
  }
  db(1,1);
  
  //// Extra code to avoid having to cycle for the last word
  //Note: remove this part to get an actual de Bruijn sequence
  var extra= '';
  for(var i= 0, nremain= wordlength-1 ; nremain>0 ; i += 2, --nremain)
    extra += res[i % res.length] + ' ';
  res += extra;
  ////
  console.log(res);
  return res;
}

debruijn('谢谢你',3)

